package com.manong.config.security.service;

import com.manong.config.redis.RedisService;
import com.manong.entity.Permission;
import com.manong.entity.User;
import com.manong.service.PermissionService;
import com.manong.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.AbstractList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户认证处理类
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {

    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private RedisService redisService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户或密码错误!");
        }
        // 从redis中获取权限列表，若不存在则从mysql中获取,并缓存到redis中
        List<Permission> out = (List<Permission>)redisService.getOut(username);
        if(out==null){
            List<Permission> permissionListByUserId = permissionService.getPermissionListByUserId(user.getId());
            redisService.set(username,permissionListByUserId);
            //使用stream流获取权限列表中的code字段
            List<String> collect = permissionListByUserId.stream().filter(Objects::nonNull)
                    .map(Permission::getCode).filter(Objects::nonNull)
                    .collect(Collectors.toList());   //过滤
            String[] array = collect.toArray(new String[collect.size()]);
            List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(array);
            //设置权限列表
            user.setAuthorities(authorityList);
            user.setPermissionList(permissionListByUserId);
        }else {
            //使用stream流获取权限列表中的code字段
            List<String> collect = out.stream().filter(Objects::nonNull)
                    .map(Permission::getCode).filter(Objects::nonNull)
                    .collect(Collectors.toList());   //过滤
            String[] array = collect.toArray(new String[collect.size()]);
            List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(array);
            //设置权限列表
            user.setAuthorities(authorityList);
            user.setPermissionList(out);
        }
        return user;
    }
}
